import { defineStore } from "pinia";
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  type LoginData,
} from "@/api/user";
import { getFuncList, type FuncTreeNode } from "@/api/menu";
import { setToken, clearToken } from "@/utils/auth";
import { removeRouteListener } from "@/utils/route-listener";
import type { UserState } from "./types";
import type { AppRouteRecordRaw } from "@/router/routes/types";

const useUserStore = defineStore("user", {
  state: (): UserState => ({
    userId: localStorage.getItem("userId")
      ? Number(localStorage.getItem("userId"))
      : undefined,
    name: localStorage.getItem("name") || "",
    iphone: "",
    policeNum: "",
    role: localStorage.getItem("role")
      ? Number(localStorage.getItem("role"))
      : undefined,
    group: localStorage.getItem("group")
      ? Number(localStorage.getItem("group"))
      : undefined,
    groupName: localStorage.getItem("groupName") || "",
    dept: undefined,
    menus: (() => {
      try {
        const menus = localStorage.getItem("menus");
        return menus ? JSON.parse(menus) : [];
      } catch (e) {
        return [];
      }
    })(),
    createTime: undefined,
    updateTime: undefined,
    groupId: undefined,
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === "user" ? "admin" : "user";
        localStorage.setItem("role", this.role.toString());
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info(res: any) {
      this.setInfo(res);
    },

    // 获取功能菜单列表并转换为路由格式
    async getFuncMenus() {
      try {
        const res = await getFuncList();
        if (res.code === 200 && res.data) {
          // 将后端返回的树结构转换为路由格式
          const routes = this.convertFuncTreeToRoutes(res.data.funcList);
          this.menus = routes;
          localStorage.setItem("menus", JSON.stringify(routes));
          return routes;
        } else {
          console.error("获取功能菜单失败:", res.message);
          return [];
        }
      } catch (error) {
        console.error("获取功能菜单失败:", error);
        return [];
      }
    },

    // 将功能树转换为路由格式
    convertFuncTreeToRoutes(funcTree: FuncTreeNode[]): AppRouteRecordRaw[] {
      // 路径映射表，将funcPath映射到实际的组件路径
      const pathMapping: Record<string, string> = {
        "/supervision/query": "supervision/task",
        "/user/query": "user/userinfo",
        "/role/query": "role/roleinfo",
        "/group/query": "group/groupinfo",
      };

      // 页面路径映射表，将funcPath映射到实际的页面路径
      const pagePathMapping: Record<string, string> = {
        "/supervision/query": "/supervision/task",
        "/user/query": "/user/management",
        "/role/query": "/role/management",
        "/group/query": "/system/organization",
      };

      // 使用简单的路由名称，避免冲突
      const nameMapping: Record<string, string> = {
        系统管理: "system",
        督察管理: "supervision",
        用户管理: "user-management",
        角色管理: "role-management",
        组织架构管理: "organization-management",
        督察任务管理: "supervision-management",
      };

      // 图标映射表，常见菜单指定icon
      const iconMapping: Record<string, string> = {
        系统管理: "icon-settings",
        用户管理: "icon-user",
        角色管理: "icon-skin",
        组织架构管理: "icon-relation",
        督察管理: "icon-list",
        督察任务管理: "icon-thunderbolt",
      };
      // 图标池，依次分配
      const iconPool = [
        "icon-apps",
        "icon-list",
        "icon-settings",
        "icon-user",
        "icon-check-circle",
        "icon-exclamation-circle",
        "icon-file",
        "icon-notification",
        "icon-tag",
        "icon-folder-delete",
        "icon-swap",
        "icon-to-left",
        "icon-to-right",
        "icon-refresh",
        "icon-close",
        "icon-sun-fill",
        "icon-moon-fill",
        "icon-export",
        "icon-language",
        "icon-github",
        "icon-fullscreen",
        "icon-fullscreen-exit",
      ];
      let iconIndex = 0;
      function assignIcon() {
        const icon = iconPool[iconIndex % iconPool.length];
        iconIndex++;
        return icon;
      }

      function walk(nodes: FuncTreeNode[]): AppRouteRecordRaw[] {
        return nodes.map((node) => {
          const isParentRoute = node.children && node.children.length > 0;
          const routeName =
            nameMapping[node.funcName] ||
            `route-${node.funcName.toLowerCase()}`;
          let routePath: string;
          if (isParentRoute) {
            routePath = `/${node.funcName.toLowerCase()}`;
          } else {
            routePath =
              pagePathMapping[node.funcPath || ""] ||
              `/${node.funcName.toLowerCase()}`;
          }
          let componentPath: string;
          if (isParentRoute) {
            componentPath = "LAYOUT";
          } else {
            componentPath = pathMapping[node.funcPath || ""] || "LAYOUT";
          }
          const route: AppRouteRecordRaw = {
            name: routeName,
            path: routePath,
            component: componentPath,
            redirect:
              isParentRoute && node.children && node.children.length > 0
                ? pagePathMapping[node.children[0].funcPath || ""] ||
                  `/${node.children[0].funcName.toLowerCase()}`
                : undefined,
            meta: {
              title: node.funcName,
              locale: node.funcName,
              icon: iconMapping[node.funcName] || assignIcon(),
              orderNo: node.index || 0,
              hideMenu: false,
              hideBreadcrumb: false,
              currentActiveMenu: "",
              ignoreKeepAlive: false,
              ignoreAuth: false,
              hideTab: false,
              frameSrc: "",
              canTo: false,
              ignoreRoute: false,
              hideChildrenInMenu: false,
              affix: false,
              dynamicLevel: 3,
              realPath: "",
              requiresAuth: true,
              roles: ["*"],
            },
          };
          if (node.children && node.children.length > 0) {
            route.children = walk(node.children);
          }
          return route;
        });
      }
      const routes = walk(funcTree);
      // 排序：系统管理放在第一位
      routes.sort((a, b) => {
        if (a.meta?.title === "系统管理") return -1;
        if (b.meta?.title === "系统管理") return 1;
        return (Number(a.meta?.orderNo) || 0) - (Number(b.meta?.orderNo) || 0);
      });
      return routes;
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.data.token);
        // 直接用登录返回的数据
        this.setUserInfo({
          role: res.data.roleId,
          userId: res.data.userId,
          name: res.data.userName,
          group: res.data.groupId,
          groupName: res.data.groupName,
        });
        return res;
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      this.resetInfo();
      clearToken();
      removeRouteListener();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
    setUserInfo(info) {
      this.role = info.role !== undefined ? Number(info.role) : undefined;
      localStorage.setItem(
        "role",
        this.role !== undefined ? String(this.role) : ""
      );
      this.userId = info.userId;
      this.name = info.name;
      this.group = info.group;
      this.groupName = info.groupName;
      localStorage.setItem(
        "userId",
        this.userId !== undefined ? String(this.userId) : ""
      );
      localStorage.setItem("name", this.name !== undefined ? this.name : "");
      localStorage.setItem(
        "group",
        this.group !== undefined ? String(this.group) : ""
      );
      localStorage.setItem(
        "groupName",
        this.groupName !== undefined ? this.groupName : ""
      );
      this.setInfo(info);
    },
    setMenus(menus) {
      this.menus = menus;
      localStorage.setItem("menus", JSON.stringify(menus));
    },
    restoreFromLocal() {
      const role = localStorage.getItem("role");
      this.role = role ? Number(role) : undefined;
      const userId = localStorage.getItem("userId");
      this.userId = userId ? Number(userId) : undefined;
      this.name = localStorage.getItem("name") || "";
      const group = localStorage.getItem("group");
      this.group = group ? Number(group) : undefined;
      this.groupName = localStorage.getItem("groupName") || "";
      try {
        const menus = localStorage.getItem("menus");
        this.menus = menus ? JSON.parse(menus) : [];
      } catch (e) {
        this.menus = [];
      }
    },
    clearUserInfo() {
      this.role = undefined;
      this.menus = [];
      localStorage.removeItem("role");
      localStorage.removeItem("menus");
    },
  },
});

export default useUserStore;
